package com.starblink.android.basic.user.login

import android.content.Context
import android.content.Intent
import androidx.fragment.app.FragmentActivity
import com.google.android.gms.auth.GoogleAuthUtil
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.Scopes
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.starblink.android.basic.ext.commContext
import com.starblink.basic.util.log.YYLogUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

object GoogleLoginUtils {
    const val SERVER_CLIENT_ID =
        "132150157594-sech8dvq8gvfe2ma74qq9ahcgj12h6m1.apps.googleusercontent.com"

    private var googleSignInClient: GoogleSignInClient? = null
        get() {
            if (field == null) {
                val googleSignInOptions = GoogleSignInOptions
                    .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(SERVER_CLIENT_ID) // 参考Google Cloud-凭据-Web Client
                    .requestEmail() //获取邮箱信息【不添加会影响到获取性别信息】
                    .build()
                field = GoogleSignIn.getClient(commContext(), googleSignInOptions)
            }
            return field
        }

    /**
     * 如果存在已登录的Google账号，返回true
     */
    fun isLogin(): Boolean {
        val account = GoogleSignIn.getLastSignedInAccount(commContext())
        return account != null
    }

    /**
     * 登录
     */
    fun signIn(activity: FragmentActivity, requestCode: Int) {
        val signInIntent = googleSignInClient!!.getSignInIntent()
        activity.startActivityForResult(signInIntent, requestCode)
    }

    /**
     * 登出
     */
    fun signOut(): Task<Void> {
        return googleSignInClient!!.signOut()
    }

    /**
     * 解除帐号关联
     */
    fun revokeAccess(): Task<Void> {
        return googleSignInClient!!.revokeAccess()
    }

    /**
     * 处理谷歌登录结果
     */
    fun handleGoogleSignInResult(
        data: Intent?,
        onSuccess: (GoogleSignInAccount) -> Unit,
        onFail: (ApiException) -> Unit
    ) {
        try {
            val task: Task<GoogleSignInAccount> = GoogleSignIn.getSignedInAccountFromIntent(data)
            val account = task.getResult(ApiException::class.java)
            val info = "获取登录信息成功：" + "\n" +
                    "ID：" + account.getId() + "\n" +
                    "idToken：" + account.idToken + "\n" +
                    "photoUrl：" + account.getPhotoUrl() + "\n" +
                    "email：" + account.email + "\n" +
                    "displayName：" + account.getDisplayName() + "\n" +
                    "familyName：" + account.getFamilyName() + "\n" +
                    "givenName：" + account.getGivenName() + "\n" +
                    "serverAuthCode：" + account.serverAuthCode
            YYLogUtils.i(info, "dss")
            onSuccess(account)
        } catch (e: ApiException) {
            YYLogUtils.i(e.toString(), "dss")
            onFail(e)
        }
    }

    /**
     * 获取Google登录AccessToken
     * @note 需要放在子线程中执行
     */
    fun fetchGoogleAccessToken(
        email: String,
        resultCallback: (String?) -> Unit,
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                var token = GoogleAuthUtil.getToken(
                    commContext(),
                    email,
                    "oauth2:${Scopes.PROFILE} ${Scopes.EMAIL}"
                )
                YYLogUtils.i("GoogleAccessToken=$token")
                MainScope().launch{
                    resultCallback(token)
                }
            } catch (e: Exception) {
                YYLogUtils.i(e.toString())
                MainScope().launch{
                    resultCallback(null)
                }
            }
        }
    }

    /**
     * true表示手机的GooglePlay服务可用
     */
    fun isGooglePlayServicesAvailable(context: Context): Boolean {
        return GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) == 0
    }
}